<?php
/**
 * Created by PhpStorm.
 * User: apple
 * Date: 2020/10/12
 * Time: 4:06 PM
 */
namespace app\index\logic;


use app\event\ModifyIntegral;
use app\model\IntegralLog;
use app\model\UserVideo;
use app\model\Video;
use think\facade\Db;

class VideoLogic
{

    public function getVideoList(){

        $orgId = config('user')['orgid'];

        $where = [
            'v_orgid' => $orgId,
            'v_status' => 1
        ];
        $videoModel = new Video();

        return $videoModel->getVideoListByCondition($where);
    }
    //播放
    public function play(){

        $uid = config('user')['id'];

        $videoId = input('videoId');

        $videoModel = new Video();
        $videoInfo = $videoModel->getVideoInfoById($videoId);
        if(!$videoInfo) fail('视频信息不存在');

        $userVideoModel = new UserVideo();
        $play = $userVideoModel->getUserLastPlayInfoByUidAndVideoId($uid,$videoId);

        //是否赠送积分
        $integralFlag = true;
        if($play){
            //存在播放记录 同月就不送积分
            if(date('Y-m',$play['uv_create_time']) == date('Y-m'))   $integralFlag = false;
        }
        //随机增加积分
        $num = 0;
        Db::startTrans();
        try {
            //add 播放记录
            $playData = [
                'uv_uid' => $uid,
                'uv_vid' => $videoId,
            ];
            $playRet = $userVideoModel->addOnePlay($playData);
            if(!$playRet){
                Db::rollback();
            }
            //add 视频播放数量
            $numRet = $videoModel->addVideoPlayNum($videoId);
            if(!$numRet){
                Db::rollback();
            }


            if($integralFlag){
                $num = event(new ModifyIntegral(IntegralLog::PLAY_VIDEO,$videoId,$videoInfo['v_name']));
                $num = is_array($num) ? $num[0] : $num;
//                $num = mt_rand(1,5);
//                $integralLog = [
//                    'integral_uid' => $uid,
//                    'integral_way' => $videoId,
//                    'integral_type' => IntegralLog::PLAY_VIDEO,
//                    'integral_num' => $num,
//                    'integral_remark' => '观看视频'.$videoInfo['v_name']
//                ];
//                $integralLogModel = new IntegralLog();
//                $addRet = $integralLogModel->addLog($integralLog);
//                if(!$addRet){
//                    Db::rollback();
//                }
//
//                //修改客户总积分
//                $userModel = new User();
//                $userModel->addUserIntegral($uid,$num);
            }

            Db::commit();
        } catch (\Exception $e){
            Db::rollback();
        }

        return intval($num);
    }

}